package com.demo.crm.security.filter;

import com.demo.crm.model.UserToken;

import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;

/**
 * 未登录用户过滤器
 *
 * @author tanshuai
 */
public class NotLoggedInFilter extends GenericFilterBean {

    private String loginUrl;
    private String timeOutUrl;

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    public void setTimeOutUrl(String timeOutUrl) {
        this.timeOutUrl = timeOutUrl;
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (UserToken.getUserToken(request) == null) {
            if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
                request.getSession(true);
                ExceptionFilter.handleFailure("当前会话已过期，请重新登录", timeOutUrl, request, servletResponse);
            } else {
                ExceptionFilter.handleFailure("当前用户未登录", loginUrl, request, servletResponse);
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
